<template>
  <el-card class="content-card">
    <div class="el-descriptions__header">
      <div class="el-descriptions__title">结算账户</div>
    </div>

    <el-form ref="formRef" :disabled="readonly" :model="model" :rules="formRules" label-width="120px">
      <el-form-item label="账户类型：" prop="type">
        <!-- 企业类型 1:企业商户 2:个体工商户 3:小微商户 -->
        <el-radio-group v-model="model.type" @change="handleChangeType">
<!--           -->
          <el-radio-button  :value="1"  v-if="companyType == 2 || companyType == 1">对公账户</el-radio-button>
          <el-radio-button :value="2"  v-if="companyType ==3 || companyType == 2" >对私法人</el-radio-button>
          <el-radio-button :value="3"  v-if="companyType == 2">对私非法人</el-radio-button>

        </el-radio-group>
      </el-form-item>


      <template v-if="model.type === 3 || model.type === 2">
        <el-form-item :rules="[{required: true, message: '请上传银行卡正面照', trigger: 'blur'}]" label="银行卡正面：" prop="front_url">
          <UploadImage v-model="model.front_url" :disabled="readonly" :show-delete="true" :show-tip="false" @change="handleUploadBankCard"/>
        </el-form-item>
      </template>

      <el-form-item v-if="model.type === 1" :rules="[{required: true, message: '请上开户许可证', trigger: 'blur'}]" label="开户许可证：" prop="certificate">
        <UploadImage v-model="model.certificate" :disabled="readonly" :show-delete="true" :show-tip="false" @change="handleUploadBankAccountLicense"/>
      </el-form-item>

      <template v-if="model.type === 1">
        <el-form-item :rules="[{required: true, message: '开户名称不能为空', trigger: 'blur'}]" label="开户名称：" prop="account_name">
          <el-input v-model="model.account_name" placeholder="请输入开户名称"/>
        </el-form-item>
        <el-form-item :rules="[{required: true, message: '账户号码不能为空', trigger: 'blur'}]" label="账户号码：" prop="bank_num">
          <el-input v-model="model.bank_num" placeholder="请输入账户号码"/>
        </el-form-item>
      </template>

      <template v-if="model.type === 3 || model.type === 2">
        <el-form-item :rules="[{required: true, message: '银行卡号不能为空', trigger: 'blur'}]" label="银行卡号：" prop="bank_num">
          <el-input v-model="model.bank_num" placeholder="请输入银行卡号"/>
        </el-form-item>
      </template>
      <template v-if="model.type === 3 || model.type === 2">
        <el-form-item :rules="[{required: true, message: '手机号不能为空', trigger: 'blur'}]" label="手机号：" prop="phone">
          <el-input v-model="model.phone" placeholder="请输入手机号"/>
        </el-form-item>
      </template>
      <el-form-item :rules="[{required: true, message: '请选择开户地区', trigger: 'blur'}]" label="开户地区：" prop="city_id">
        <TreeSelect ref="regionTreeRef"
                    v-model="city_name"
                    :tree-data="areaData"
                    title="请选择开户地区"
                    @selectChange="handleChangeRegion"/>
      </el-form-item>
      <el-form-item :rules="[{required: true, message: '开户银行不能为空', trigger: 'blur'}]" label="开户银行：" prop="bank_name">
        <el-input v-model="model.bank_name" placeholder="请输入银行名称"/>
      </el-form-item>

      <el-form-item :rules="[{required: true, message: '请选择开户支行', trigger: 'blur'}]" label="开户支行：" prop="bank_branch">
        <BankBranchSearch ref="bankBranchRef"
                          v-model="model.bank_branch"

                          :readonly="readonly"
                          :limit="100"
                          placeholder="请选择开户支行"
                          @change="handleChangeBankBranch"/>
      </el-form-item>



    </el-form>
  </el-card>
</template>

<script lang="ts" setup>

import { nextTick, reactive, ref, watch,onMounted } from 'vue';
import { ElLoading, FormInstance, FormRules ,ElTreeSelect} from 'element-plus';
import { UploadImage } from '@/components/upload';
import { ocrRecognize } from '@/api/api-common.ts';
import { BankBranchSearch } from '@/components/other';
import { BankBranchData } from '@/components/other/src/bank-branch-search.vue';
import { TreeSelect } from '@/components/tree-select';
import addressList from '@/utils/address.ts';
import { SettlementAccount } from '@/api/common.ts';

const model = defineModel<SettlementAccount>({required: true});
const props = defineProps({
  shopType: {
    type: Number,
  },
  companyType: {
    type: Number
  },
  readonly: {
    type: Boolean,
    default: false
  },
  areaData:{
    type:Array
  }
});
const city_name=ref('')
/** 监听公司类型 1:企业商户 2:个体工商户 3:小微商户 */
watch(() => props.companyType, async (val: any) => {
    console.log(val)
      if (val === 1) {
        // 默认设置 对公账户
        if (model.value.type != 1) {
          model.value.type = 1;
         await handleChangeType();
        }
      } else if (val === 2) {
        if (!model.value.type) {
          model.value.type = 1;
          await handleChangeType();
        }
      } else if (val === 3) {
        // 默认设置 对私法人
        if (model.value.type != 2) {
          model.value.type = 2;
          await handleChangeType();
        }
      }
    },
    {immediate: true}
);

const formRef = ref<FormInstance>();
const formRules = reactive<FormRules>({
  type: [{required: true, message: '请选择账户类型', trigger: 'blur'}],
})
/** 表单重置 */
const formReset = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
};

/** 表单验证 */
const formValidate = () => {
  if (!formRef.value) return
  return formRef.value.validate()
};

/** 对外提供方法 */
defineExpose({
  formReset,
  formValidate,
});

const bankBranchRef = ref();
const regionTreeRef = ref();
const regionOptions = addressList;
const emit = defineEmits(['AccountType']);
const handleChangeType = () => {
  formRef.value?.clearValidate();
  // 通知父组件 账户类型被改变
  emit('AccountType', model.value.type)
};

/** 处理银行卡上传完成 */
const handleUploadBankCard = async (val: any) => {
  if (val) {
    // 调用接口进行识别
    const loading = ElLoading.service({
      lock: true,
      text: '正在识别中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    try {
      let params = {type: 'bank', url: val};
      const {body} = await ocrRecognize(params,{action:'ocr'});
      // let type = data.type;
      let typeData = body;
      if (typeData) {
        model.value.bank_num = typeData.card_num;
        model.value.bank_name = typeData.bank_name;
        // model.value.city_name = '';
        // model.value.city_id = undefined;
        // 调用函数搜索
        // bankBranchRef.value?.handleRemoteMethod(model.value.bank_name);
      }
    } finally {
      loading.close();
    }
  } else {

  }
};

/** 处理开户许可证上传完成 */
const handleUploadBankAccountLicense = async (val: any) => {
  if (val) {
    // 调用接口进行识别
    const loading = ElLoading.service({
      lock: true,
      text: '正在识别中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    try {
      let params = {type: 'permit', url: val};
      const {body} = await ocrRecognize(params,{action:'ocr'});
      // let type = data.type;
      let typeData = body;
      if (typeData) {
        console.log(typeData["名称"])
        model.value.bank_num =typeData["账号"];
        model.value.account_name = typeData["名称"]
        model.value.bank_name = typeData["开户银行"];
        // model.value.branch_name = typeData.depositary_bank;
        // model.value.city_name = '';
        // model.value.city_id = undefined;
        // 调用函数搜索
        // bankBranchRef.value?.handleRemoteMethod(model.value.bank_name);
      }
    } finally {
      loading.close();
    }
  } else {

  }
};

/** 处理支行改变事件 */
const handleChangeBankBranch = (item?: BankBranchData) => {
  if (item) {
    model.value.unionpay_code = item.unionpay_code;
    // model.value.bank_name = item.bank_name;
    // model.value.province_code = item.province_code;
    // model.value.city_id = item.city_code;
    // model.value.county_code = item.county_code;
    // 处理开户地区选中
    // handleRegionSet();
  } else {
    // model.value.unionpay_code = '';
    // model.value.bank_name = '';
    // model.value.city_id = '';
  }
};

const handleChangeRegion = (item?: any) => {
  model.value.city_id = item;
};

const handleRegionSet = () => {
  nextTick(() => {
    // let code = model.value.county_code;
    // if (!code || code <= 0) {
    //   code = model.value.city_id;
    // }
    // if (!model.value.city_id) {
    //   model.value.city_id = code;
    // }
    regionTreeRef.value?.handleSetCurrentNode( model.value.city_id)
  });
}
onMounted(() => {
  setTimeout(()=>{
    handleRegionSet();
  },1000)
});
</script>

<style lang="scss" scoped>

</style>
